package co.yixiang.yshop.framework.web.core.filter;

import cn.hutool.core.util.StrUtil;
import co.yixiang.yshop.framework.common.pojo.CommonResult;
import co.yixiang.yshop.framework.common.util.servlet.ServletUtils;
import co.yixiang.yshop.framework.web.core.util.WebFrameworkUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static co.yixiang.yshop.framework.common.exception.enums.GlobalErrorCodeConstants.DEMO_DENY;

/**
 * 演示 Filter，禁止用户发起写操作，避免影响测试数据
 *
 * @author yshop
 */
public class DemoFilter extends OncePerRequestFilter {

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String method = request.getMethod();
        String path = request.getRequestURI();
        System.out.println("method:"+method);
        System.out.println("path:"+path);
        //系统模块特殊处理
        Boolean res01 = StrUtil.contains(path,"/admin-api/order/store-order/update");
        Boolean res02 = StrUtil.contains(path,"/admin-api/order/store-after-sales/update");
        Boolean res03 = StrUtil.contains(path,"/admin-api/order/store-order/writeOff");
        if(res01 || res02 || res03) {
            return true;
        }

        //营销模块放开
        Boolean res04 = StrUtil.contains(path,"/admin-api/product/campaign-info/create");
        Boolean res05 = StrUtil.contains(path,"/admin-api/product/coupon/create");
        Boolean res06 = StrUtil.contains(path,"/admin-api/distributor/distributor/verify");
        if(res04 || res05 || res06) {
            return true;
        }

        Boolean res66 = StrUtil.contains(path,"/admin-api/product/store-product/isFormatAttr");
        if(res66) {
            return true;
        }
        Boolean res67 = StrUtil.contains(path,"/admin-api/product/store-product/isSkuFormatAttr");
        if(res67) {
            return true;
        }

        Boolean res07 = StrUtil.contains(path,"/admin-api/system/auth/logout");

        Boolean res08 = StrUtil.contains(path,"/admin-api/system/auth/login");

        Boolean res09 = StrUtil.contains(path,"/admin-api/system/captcha/get");
        if(res07 || res08 || res09) {
            return true;
        }


            //old : "POST", "PUT", "DELETE"
        return !StrUtil.equalsAnyIgnoreCase(method, "POST", "PUT", "DELETE")  // 写操作时，不进行过滤率
                || !request.getRequestURI().contains("/admin-api")
                || WebFrameworkUtils.getLoginUserId(request) == null; // 非登录用户时，不进行过滤
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
        // 直接返回 DEMO_DENY 的结果。即，请求不继续
        ServletUtils.writeJSON(response, CommonResult.error(DEMO_DENY));
    }

}
